package com.artevivo.managedBeans;

import java.io.IOException;
import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import org.primefaces.event.SelectEvent;
import org.primefaces.model.LazyDataModel;
import org.springframework.stereotype.Controller;

import com.artevivo.entidades.Matricula;
import com.artevivo.services.ClienteService;
import com.artevivo.services.MatriculaService;
import com.artevivo.utilidades.LazyClienteDataModel;

@Controller(value = "buscarClientesMB")
@ViewScoped
public class BuscarClientesMB implements Serializable {

    private static final long serialVersionUID = 1L;

    private LazyDataModel<Matricula> lazyModel;

    @Resource
    private SessionManagedBean sessionMB;

    @Resource
    private ClienteService clienteService;

    @Resource
    private MatriculaService matriculaService;

    @PostConstruct
    public void init() {
        try {
            lazyModel = new LazyClienteDataModel(matriculaService.obtenerMatriculas(), clienteService, sessionMB);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public LazyDataModel<Matricula> getLazyModel() {
        return lazyModel;
    }

    public void onRowSelect(SelectEvent event) {
        String res = "ERROR";

        Matricula matriculaSeleccionada = (Matricula) event.getObject();
        this.sessionMB.setSelectedMatricula(matriculaSeleccionada);

        if (this.sessionMB.getSelectedMatricula() != null) {
            res = "fichaCliente.xhtml";
            try {
                FacesContext.getCurrentInstance().getExternalContext().redirect(res);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (res.equals("ERROR")) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "Lo sentimos, ha ocurrido un error"));
        }

    }
}